local format = string.format
local keymap = vim.api.nvim_set_keymap

local nmaps = function(lhs, rhs)
	keymap("n", lhs, rhs, { silent = true })
end

nmaps("<S-Tab>", "<Plug>(cokeline-focus-prev)")
nmaps("<Tab>", "<Plug>(cokeline-focus-next)")
nmaps("<Leader>bd", "bdelete")

for i = 1, 9 do
	nmaps(format("<Leader>%s", i), format("<Plug>(cokeline-focus-%s)", i))
end
local index = {
	text = function(buffer)
		return buffer.number .. ": "
	end,
	hl = {
		fg = function(buffer)
			if buffer.is_focused then
				return "black"
			end
			return "white"
		end,
	},
}
local error = {
	text = "  ",
	guifg = "#EC5241",
}
local warning = {
	text = "  ",
	guifg = "#EFB839",
}
local fg = function(buffer)
	if buffer.is_focused then
		return "black"
	end
	return "#FFFFFF"
end

local fg_right_arrow = function(buffer)
	if buffer.is_focused then
		return "#8BC34A"
	end
end

local diagnostic = {
	text = function(buffer)
		if buffer.lsp.errors ~= 0 then
			return error.text
		end
		if buffer.lsp.warnings ~= 0 then
			return warning.text
		end
		return ""
	end,
	hl = {
		fg = function(buffer)
			if buffer.lsp.errors ~= 0 then
				return error.guifg
			end
			if buffer.lsp.warnings ~= 0 then
				return warning.guifg
			end
		end,
	},
}

local get_hex = require("cokeline/utils").get_hex
local space = { text = " " }
require("cokeline").setup({
	cycle_prev_next_mappings = true,
	default_hl = {
		focused = {
			bg = "#8BC34A",
			fg = "white",
		},
		unfocused = {
			fg = get_hex("Comment", "fg"),
			bg = "none",
		},
	},
	components = {
		{
			text = function(buffer)
				if buffer.is_focused then
					return ""
				end
				return ""
			end,
			hl = {
				fg = "black",
			},
		},
		{
			text = function(buffer)
				return buffer.devicon.icon
			end,
			hl = {
				fg = function(buffer)
					return buffer.devicon.color
				end,
			},
		},
		index,
		{
			text = function(buffer)
				if buffer.is_focused then
					return buffer.filename .. "~" .. buffer.index
				end
				return buffer.filename .. "~" .. buffer.index
			end,
			hl = {
				fg = fg,
				style = function(buffer)
					if buffer.is_focused then
						return "underline"
					end
					return nil
				end,
			},
		},
		{
			text = function(buffer)
				if buffer.is_readonly then
					return " 🔒"
				end
				return ""
			end,
		},
		diagnostic,
		{
			text = "  ",
			delete_buffer_on_left_click = true,
			hl = {
				fg = fg,
			},
		},
		{
			text = function(buffer)
				if buffer.is_focused then
					return ""
				end
				return ""
			end,
			hl = {
				fg = "#8BC34A",
				bg = "black",
			},
		},
	},
})
